home *** CD-ROM | disk | FTP | other *** search
/ Disc to the Future 2 / Disc to the Future Part II Programmer's Reference (Wayzata Technology)(6013)(1992).bin / MAC / SMALLTAL / CATCH_&_.THR next >
Text File  |  1990-07-16  |  2KB  |  59 lines

  1. Sometimes, I've wanted catch & throw or even just the ability to break
  2. out of whiles without having to define a separate method to hold the
  3. while loop, so I wrote a simple catch & throw last night.
  4.  
  5. Here's an example of its use:
  6.  
  7.         Catcher catch:[:tag |
  8.                 true ifTrue: [tag throw: #thrown].
  9.                 #notThrown]
  10.  
  11. This class will work in any Smalltalk that I know of, because it
  12. doesn't rely on any fancy stuff, like exception handling.  It just
  13. relys on the ability to return from the method enclosing a block.
  14.  
  15. (':=' is a synonym for the assignment operator in Smalltalk 2.5, so
  16. you may have to use a global replace of ':=' for '_' or '<-,'
  17. depending on your version of Smalltalk.  Also, you may or may not have
  18. to take out all the '!'s and *** methodsFor: *** expressions.)
  19.  
  20. ----- cut here -----
  21.  
  22. Object subclass: #Catcher
  23.         instanceVariableNames: 'context '
  24.         classVariableNames: ''
  25.         poolDictionaries: ''
  26.         category: 'Goodies'!
  27.  
  28. !Catcher methodsFor: 'accessing'!
  29.  
  30. context
  31.         ^context!
  32.  
  33. context: aValue
  34.         context := aValue! !
  35.  
  36. !Catcher methodsFor: 'controlling'!
  37.  
  38. catch: aBlock
  39.         self context: [:returnValue | ^returnValue].
  40.         ^aBlock value: self!
  41.  
  42. throw
  43.         self throw: nil!
  44.  
  45. throw: value
  46.         self context value: value! !
  47. "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
  48.  
  49. Catcher class
  50.         instanceVariableNames: ''!
  51.  
  52. !Catcher class methodsFor: 'instance creation'!
  53.  
  54. catch: aBlock
  55.         ^self new catch: aBlock! !
  56. --
  57.         -- Bill Burdick
  58.         burdick@cello.ecn.purdue.edu
  59.